#'
#' plot distribution of individuals of the whole population or community
#'
#' @aliases plot.population plot.community
#'
#' @param com a community object
#' @param pop a population object
#' @param transparent the transparent of points, 0 is totally transparent. it is useful in displaying many overlaying individuals.
#' @param speciesGrid a logical flag to plot spatial distribution of each species separately in each grid.
#' @param showDBH a logical flag to assign size of each point by its correponding individual DBH
#' 
#' @note
#' the plot.population and plot.community returns a ggplot object, which can be add more control to the figure by modifying the return object
#'
#'
#' @export
plot.population=function(pop,transparent=0.5,showDBH=TRUE){
  require(ggplot2)
  plotdim=attr(pop,"plotdim")
  p=ggplot(pop,aes(x=x,y=y))
  
  if(showDBH & "dbh" %in% get_trait_names(pop)){
    p=p + geom_point( aes(size=dbh),shape=19,alpha=transparent)
  }else{
    p=p + geom_point(shape=19,alpha=transparent)
  }
  p= p +
    xlim(0,plotdim[1])+ #only display points within the plot
    ylim(0,plotdim[2])+
    coord_cartesian(xlim=c(0,plotdim[1]),ylim=c(0,plotdim[2]))+ #define the range of the plot
    theme_bw()+  #using white background color
    theme(panel.grid.major=element_blank(),
          panel.grid.minor=element_blank()) +   #remove grid lines 
    coord_fixed(xlim=c(0,plotdim[1]),ylim=c(0,plotdim[2]))  #same scale of x and y
  return(p)
}

#' @export
plot.community=function(com,transparent=0.5,speciesGrid=FALSE,showDBH=TRUE){
  require(ggplot2)
  plotdim=attr(com,"plotdim")
  if(speciesGrid){
    p=ggplot(com,aes(x=x,y=y))
  }else{
    p=ggplot(com,aes(x=x,y=y,colour=species))
  }
  if(showDBH & "dbh" %in% get_trait_names(com)){
    p=p + geom_point( aes(size=dbh),shape=19,alpha=transparent)
  }else{
    p=p + geom_point(shape=19,alpha=transparent)
  }
  p=p + 
    xlim(0,plotdim[1])+ #only display points within the plot
    ylim(0,plotdim[2])+
    coord_cartesian(xlim=c(0,plotdim[1]),ylim=c(0,plotdim[2]))+ #define the range of the plot
    theme_bw()+  #using white background color
    theme(panel.grid.major=element_blank(),
          panel.grid.minor=element_blank())+ #remove grid lines
    coord_fixed(xlim=c(0,plotdim[1]),ylim=c(0,plotdim[2]))  #same scale of x and y
    #scale_color_hue(l=45) #add colour to easy identify
  if(total_richness(com)>10){
    p=p+guides(fill=FALSE)+theme(legend.position="none") #if there are more than 10 species, just remove the legend. because it is too long
  }
  if(speciesGrid){
    p=p+facet_wrap(~ species)
  }
  return(p)
}